package com.xiaohao.communication.ESdao;

import com.xiaohao.communication.ESutils.HighlightProcessor;
import com.xiaohao.communication.ESutils.ScrollProcessor;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;

/*
 * 底层的封装方法
 * */
@Repository
public class ModernLiteratureSearch {

    private final RestHighLevelClient client;                   // es 中
    private final HighlightProcessor highlightProcessor;        //自己封装的工具类
    private final ScrollProcessor scrollProcessor;              //自己封装的工具类
    private final Scroll scroll;                                // es 中

    @Autowired
    public ModernLiteratureSearch(RestHighLevelClient client, HighlightProcessor highlightProcessor, ScrollProcessor scrollProcessor, Scroll scroll) {
        this.client = client;
        this.highlightProcessor = highlightProcessor;
        this.scrollProcessor = scrollProcessor;
        this.scroll = scroll;
    }

    /*
     * 第一次点击搜索时发送的请求
     * */
    public SearchResponse scrollSearchFirstly(String keyword) throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //高亮设置
        HighlightBuilder highlightBuilder = highlightProcessor.allFieldHighlightBuilder();
        //查询    ik_smart  : 分词器
        searchSourceBuilder.highlighter(highlightBuilder).query(new QueryStringQueryBuilder(keyword).analyzer("ik_smart")).size(10);
        //构建
        searchRequest.source(searchSourceBuilder).scroll(scroll);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //加高亮
        // TODO: 2019/1/24 然而并没有高亮
        highlightProcessor.highlightProcessor(searchResponse.getHits());
        return searchResponse;
    }

    /*
     * 点击下一页搜索时发送的请求
     * @param scrollId  :
     * */
    public SearchResponse scrollSearchSecondly(String scrollId) throws IOException {
        return scrollProcessor.scrollToNext(client, scrollId, scroll);
    }


    /*
     *  看到查询出来的信息后，点击查看详细的信息。
     * */
    public GetResponse findById(String index, String type, String id) throws IOException {
        GetRequest getRequest = new GetRequest(index, type, id);
        return client.get(getRequest, RequestOptions.DEFAULT);
    }


}
